package xzx.service.impl;

import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import xzx.bean.ChatEntity;
import xzx.bean.ChatResponseEntity;
import xzx.enums.SSEMsgType;
import xzx.service.IChatService;
import xzx.utils.SSEServer;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: ChatServiceImpl
 * @author: xzx
 * @date: 2025-10-20
 **/
@Slf4j
@Service
public class ChatServiceImpl implements IChatService {
    private final ChatClient chatClient;

    // 构造器注入，自动配置方式（推荐）
    public ChatServiceImpl(ChatClient.Builder chatClientBuilder, ToolCallbackProvider tools, ChatMemory chatMemory) {

        /**
         * 提示词的三大类型
         *  1. system
         *  2. user
         *  3. assistant
         */
        String systemPrompt = """
                    你是一个非常专业的农机监理业务人工智能助手，可以帮我解决很多问题，我为你取一个名字，你的名字叫‘LaGoGo’。
                """;
        this.chatClient = chatClientBuilder
                .defaultToolCallbacks(tools)
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                .defaultSystem(systemPrompt)
                .build();
    }
    @Override
    public Flux<String> chatTest1(String message) {
        return chatClient.prompt(message).stream().content();
    }

    @Override
    public void doChat(ChatEntity chatEntity) {
        String userId = chatEntity.getCurrentUserName();
        String prompt = chatEntity.getMessage();
        String botMsgId = chatEntity.getBotMsgId();

        Flux<String> stringFlux = chatClient.prompt(prompt).stream().content();

        List<String> list = stringFlux.toStream().map(chatResponse -> {
            String content = chatResponse.toString();
            SSEServer.sendMsg(userId, content, SSEMsgType.ADD);
            log.info("content: {}", content);
            return content;
        }).collect(Collectors.toList());

        String fullContent = list.stream().collect(Collectors.joining());

        ChatResponseEntity chatResponseEntity = new ChatResponseEntity(fullContent, botMsgId);

        SSEServer.sendMsg(userId, JSONUtil.toJsonStr(chatResponseEntity), SSEMsgType.FINISH);
    }

    @Override
    public Flux<String> doChatTest1(String message,Long chatId) {

        return chatClient.prompt(message).advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId)).stream().content();
    }
}
